package com.koala.utils;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author yantingrui
 * @date 2021/12/7   17:03
 */
public class ObjectUtils {

    /**
     * 比较两个对象值不同属性  获得属性列表  hash 作为属性名替换参照表
     * @Params hash  对比参照表
     * @author  yantingrui
     * @time  2021/7/19 11:30
     */
    public static List<String> compare(Object o1, Object o2, HashMap<String,String> hash) throws IllegalAccessException {

        List<String> res = new ArrayList<>();
        HashMap<String, Field> fieldHashMapO1 = new HashMap<>();
        HashMap<String, Field> fieldHashMapO2 = new HashMap<>();
        for (Field field : o1.getClass().getDeclaredFields()) {
            fieldHashMapO1.put(field.getName(), field);
        }
        for (Field field : o2.getClass().getDeclaredFields()) {
            fieldHashMapO2.put(field.getName(), field);
        }
        try{
            for (Map.Entry<String, String> entry : hash.entrySet()) {
                String fieldName = entry.getKey();
                String desc = entry.getValue();
                Field o1field = fieldHashMapO1.get(fieldName);
                Field o2field = fieldHashMapO1.get(fieldName);
                if (o1field != null && o2field != null) {
                    o1field.setAccessible(true);
                    o2field.setAccessible(true);
                    if(!Objects.equals(o1field.get(o1),o2field.get(o2))){
                        res.add(desc);
                    }
                }
            }
        } catch (Exception e) {
            System.out.println(e);
        }
        return res;
    }

}
